package com.example.loadpictureshw;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Scanner;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {
	private static final int APP_PICTURES = 9;
	
	/**
	 * From a given URL, download its content to a file.
	 */
	public void loadFile(String url, File file) throws IOException {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		HttpResponse response = httpclient.execute(httpget);
		HttpEntity entity = response.getEntity();

		if (entity != null) {
			InputStream instream = entity.getContent();
			OutputStream os = new FileOutputStream(file);
			int data;
			try {
				while ((data = instream.read()) != -1) {
					os.write(data);
					os.flush();
				}
			} finally {
				instream.close();
				os.close();
			}
		}
	}
	
	/** Get all the pictures' links and save them to an ArrayList */
	public ArrayList<String> getLinksFromFile(File file) throws FileNotFoundException {
		Scanner sc = new Scanner(file);
		Gson gson = new GsonBuilder().setPrettyPrinting().create();
		
		ArrayList<String> list = new ArrayList<String>();
		StringBuffer sbuffer = new StringBuffer();

		while (sc.hasNext())
			sbuffer.append(sc.nextLine());

		JsonObject obj = gson.fromJson(sbuffer.toString(), JsonObject.class);
		
		for (int i = 0; i < APP_PICTURES; i++) {
			String link = obj.getAsJsonArray("items").get(i).getAsJsonObject()
				.get("media").getAsJsonObject().get("m").toString();
			link = link.substring(1, link.length() - 1);
			list.add(link);
		}
		
		System.out.println(list);

		return list;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		try {
			loadFile("http://ycpi.api.flickr.com/services/feeds/photos_public.gne?format=json&tags=dog", new File("Dogs.json"));
			ArrayList<String> list = getLinksFromFile(new File("Dogs.json"));
			for (int i = 0; i < APP_PICTURES; i++) {
				loadFile(list.get(i), new File("Dog" + (i + 1) + ".png"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
